package dnl.proj.rami.license;

import com.thoughtworks.xstream.XStream;
import org.apache.commons.io.FileUtils;
import org.jasypt.util.text.BasicTextEncryptor;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by User on 6/12/2014.
 */
public class LicenseManager {

    XStream xStream = new XStream();
    BasicTextEncryptor basicTextEncryptor;
    DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");

    public LicenseManager() {
        basicTextEncryptor = new BasicTextEncryptor();
        basicTextEncryptor.setPassword("Ramis_+Trick");
    }

    public String getLicenseFor(String user) {
        String date = formattedDate();
        LicenseDetails licenseDetails = new LicenseDetails(user, date);
        String encrypted = encryptLicenseDetails(licenseDetails);
        return encrypted;
    }

    private String formattedDate() {
        return dateFormat.format(new Date());
    }

    private String encryptLicenseDetails(LicenseDetails licenseDetails) {
        String s = xStream.toXML(licenseDetails);
        return basicTextEncryptor.encrypt(s);
    }

    public boolean checkLicense(String s) {
        LicenseDetails licenseDetails = getLicenseDetails(s);
        try {
            Date licenseDate = dateFormat.parse(licenseDetails.getDate());
            long licenseDateMillis = licenseDate.getTime();
            long now = System.currentTimeMillis();
            return now - licenseDateMillis < 3 * 24 * 60 * 60 * 1000;
        } catch (ParseException e) {
            e.printStackTrace();
            return false;
        }
    }

    public LicenseDetails getLicenseDetails(File file) {
        try {
            String s = FileUtils.readFileToString(file);
            return getLicenseDetails(s);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private LicenseDetails getLicenseDetails(String s) {
        String decrypted = basicTextEncryptor.decrypt(s);
        return (LicenseDetails) xStream.fromXML(decrypted);
    }

    public void installLicense(LicenseDetails licenseDetails) {
        licenseDetails.setInstallationDate(formattedDate());
        String encrypted = encryptLicenseDetails(licenseDetails);
        File licenseFile = getLicenseFile();

        try {
            FileUtils.write(licenseFile, encrypted);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private File getLicenseFile() {
        String userHome = System.getProperty("user.home");
        File userHomeDir = new File(userHome);
        return new File(userHomeDir, "rami.license");
    }

    public boolean isLicenseInstalled(){
        File licenseFile = getLicenseFile();
        return licenseFile.exists();
    }
}
